layui.define(['table', 'form', 'jquery','laytpl','laypage','element','selectInput'], function(exports) {
	"use strict";

	/**
	 * 常用封装类
	 * */
	var MOD_NAME = 'mycomm',
		$ = layui.jquery,
		table = layui.table,
		form = layui.form,
		element = layui.element,
		laytpl = layui.laytpl,
		laypage = layui.laypage;
        selectInput = layui.selectInput;
    
    //初始化复制组件
    initCopyFunction();
    
	var obj = new function() {
		
		this.ajax = function(url,data={},$type='GET',$success,$error,$complete){
			$.ajax({
				url:url,
				data:data,
				dataType: 'json',
				type: $type,
				success: function(res) {
					if(res.code==0 || res.code==200){
						if(typeof $success == "function"){
							$success(res);
						}
					}else{
						Alert(res.msg,'error',3);
						if(typeof $error == "function"){
							$error(res);
						}
					}
				},
				error:function(res){
					console.log("ERROR-file:" + res.responseJSON.traces[0].file);
					console.log("ERROR-line:" + res.responseJSON.traces[0].line);
					Alert(res.responseJSON.message,'error',5);
					if(typeof $error == "function"){
						$error(res);
					}
				},
				complete:function(e){
					load_hide();
					if(typeof $complete == "function"){
						$complete(e);
					}
				}
			})
		}
		
		this.get = function (url,data={},$success,$error,$complete){
			this.ajax(url,data,'GET',$success,$error,$complete);
		}
		
		this.post = function (url,data={},$success,$error,$complete){
			this.ajax(url,data,'POST',$success,$error,$complete);
		}
		
		//修改表格内容
		this.tableSetVal = function($url,callback=null,$table='dataTable') {
			table.on('edit('+$table+')', function(obj) {
				let value = obj.value;	//修改后的数据
				let field = obj.field;	//修改的字段名
				let data = obj.data;	//修改的当行数据
				let id = data.id;
				let loading = layer.load();
				let td = $(obj.tr.selector +" [data-field=" + field + "]");
			    $.ajax({
			        url:$url + 'setValue',
			        data:{
						id:id,
						field:field,
						value:value,
					},
			        dataType: 'json',
			        type: 'POST',
			        success: function(res) {
			            layer.close(loading);
			            //判断有没有权限
			            if(res && res.code==999){
			                Alert(res.msg);
							td.addClass('pear-btn-danger');
			                return false;
			            }else if (res.code==200) {
			                //Alert(res.msg,'success',1);
							td.addClass('pear-btn-primary');
			            } else {
			                Alert(res.msg,'error',3);
							td.addClass('pear-btn-danger');
			            }
						if(callback!=null) callback(res);
			        }
			    })
			});
		}
				
		//初始化表格
		this.tableInit = function($name,$model_path,$cols,$ext={},$table='dataTable'){
			//模块标题、模块路径、表格头部参数、表格渲染扩展参数、表格ID
			this.tableRender($name,$model_path,$cols,$ext,$table);
			this.tableTool($name,$model_path,$table);
			this.tableToolBar($name,$model_path,$table);
			this.search_table($table);
			this.tableSetVal($model_path);
			this.formSwitch('status',$model_path);
		}
		
		//初始化数据恢复表格
		this.tableRecycle = function($name,$model_path,$cols,$table='dataTable'){
			//模块标题、模块路径、表格头部参数、表格ID
			this.recycleRender($name,$model_path,$cols,$table);
			this.tableToolBar($name,$model_path,$table);
			this.search_table($table);
		}
		
		//表格渲染
		this.tableRender = function($name,$model_path,$cols,$ext={},$table='dataTable'){
			var $conf={
				elem: '#'+$table,
				url: $model_path + 'index',
				page: true,
				cols: $cols,
				cellMinWidth: 100,
				even:true,
				limit:20,
				toolbar: '#toolbar',
				defaultToolbar: [{
					title: '刷新',
					layEvent: 'refresh',
					icon: 'layui-icon-refresh',
				}, 'filter', 'print', 'exports'],
				done: function (res, curr, count) {
					//解决固定列对不齐问题
					$(".layui-table-main tr").each(function (index, val) {
						$(".layui-table-fixed").each(function () {
							$($(this).find(".layui-table-body tbody tr")[index]).height($(val).height());
						});
					});
					$(".layui-table-header tr").each(function (index, val) {
						$(".layui-table-fixed").each(function () {
							$($(this).find(".layui-table-header thead tr")[index]).height($(val).height());
						});
					});
				}
			}
			$.extend($conf,$ext);
			table.render($conf);
		}
		
		//恢复数据表格渲染
		this.recycleRender = function($name,$model_path,$cols,$table='dataTable'){
			table.render({
				elem: '#'+$table,
				url: $model_path + 'recycle',
				page: true,
				cols: $cols,
				cellMinWidth: 100,
				even:true,
				limit: 20,
				toolbar: '#toolbar',
				defaultToolbar: [{
					title: '刷新',
					layEvent: 'refresh',
					icon: 'layui-icon-refresh',
				}, 'filter', 'print', 'exports']
			});
		}
		
		//控制表格事件
		this.tableTool = function($name,$model_path,$table='dataTable',$other){
			var self = this;
			table.on('tool(' + $table + ')', function(obj) {
				if (obj.event === 'remove') {
					self.tool_remove(obj,$name,$model_path);
				} else if (obj.event === 'edit') {
					let size=$(this).attr('popsize');
					if(size==undefined) size = '';
					tool_edit(obj,$name,$model_path,size);
				} else if (obj.event === 'pop'){
					let url=$(this).attr('url');
					let title=$(this).attr('poptitle');
					let size=$(this).attr('popsize');
					self.tool_pop(url,title,size);
				} else if (obj.event === 'jump'){
					let url=$(this).attr('url');
					let title=$(this).attr('poptitle');
					top.layui.admin.jump('content',title,url,true);
				} else if (obj.event === 'link'){
					let url=$(this).attr('url');
					window.open(url); 
				}else{
					$other(obj);
				}
			});
		}
		
		//控制表头事件
		this.tableToolBar = function($name,$model_path,$table='dataTable',$other){
			var self = this;
			table.on('toolbar(' + $table + ')', function(obj) {
				if (obj.event === 'add') {
					let size=$(this).attr('popsize');
					if(size==undefined) size = '';
					tool_add($name,$model_path,size);
				} else if (obj.event === 'refresh') {
					tool_refresh($table);
				} else if (obj.event === 'batchRemove') {			//软删除
					tool_batchRemove(obj,$name,$model_path,$table);
				} else if (obj.event === 'batchRemove2') {			//真删除
					tool_batchRemove2(obj,$name,$model_path,$table);
				} else if (obj.event === 'recycle') {
					tool_recycle($model_path,$table);
				} else if (obj.event === 'batchRecovery') {
					tool_batchRecovery(obj,$name,$model_path,$table);
				} else if (obj.event === 'pop'){
					let url=$(this).attr('url');
					let title=$(this).attr('poptitle');
					let size=$(this).attr('popsize');
					self.tool_pop(url,title,size);
				} else if (obj.event === 'jump'){
					let url=$(this).attr('url');
					let title=$(this).attr('poptitle');
					top.layui.admin.jump('content',title,url,true);
				} else if (obj.event === 'link'){
					let url=$(this).attr('url');
					window.open(url); 
				}else{
					if(typeof $other == "function"){
						$other(obj);
					}
				}
			});
		}
		
		//查询表格关键词
		this.search_table = function($table){
			form.on('submit(query)', function(data) {
				table.reload($table, {
					where: data.field,
					page:{curr: 1}
				})
				return false;
			});
		}
		
		//查询表格关键词
		this.formSwitch = function($name,$model_path){
			form.on("switch(" + $name + ")", function(data) {
				var status = data.elem.checked?1:0;
				var id = this.value;
				var load = layer.load();
				$.post($model_path + "status",{[$name]:status,id:id},function (res) {
					layer.close(load);
					//判断有没有权限
					if(res && res.code==999){
						layer.msg(res.msg, {
							icon: 5,
							time: 2000, 
						})
						return false;
					}else if (res.code==200){
						Alert(res.msg,'success',1);
					} else {
						Alert(res.msg,'error',3,function(){
							$(data.elem).prop("checked",!$(data.elem).prop("checked"));
							form.render()
						});
					}
				})
			});
		}
		
		
		//自定义弹窗
		this.tool_pop = function(url,name,size='') {
			if(size=='' || size==undefined) size=0.8
			layer.open({
				type: 2,
				maxmin: true,
				title: name,
				shade: 0.1,
				area: screen(size),
				content: url
			});
		}
		
		//自定义模板
		// 模块url，附带参数，模板ID，输出ID，分页数，渲染后函数，默认页码
		this.table_tpl = function ($url,$post={},$tpl_id,$box,$limit=20,$render=function(){},$page=1){
			let pageData={page:$page,limit:$limit,count:0};
			let than=this;
			let data=$.extend($post,{page:pageData.page,limit:pageData.limit});
			
			this.get($url,data,function(res){
				pageData.count=res.count;
				var data = {"data":res.data}
				var getTpl = $tpl_id.innerHTML;
				laytpl(getTpl).render(data, function(html){
					$($box).html(html);
					$render();
				});
				
				// 首次初始化分页
				if(pageData.page==1){
					laypage.render({
					    elem: 'layui-page-box',
						count: pageData.count,
						limit: pageData.limit,
						layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
						jump: function(obj,first){
							if(!first){
								than.table_tpl($url,$post,$tpl_id,$box,obj.limit,$render,obj.curr);
							}
						}
					});
				}
			});
		} 
		
		//添加页面
		function tool_add($name,$model_path,size='') {
			layer.open({
				type: 2,
				maxmin: true,
				title: '新增' + $name,
				shade: 0.1,
				area: screen(size),
				content: $model_path + 'add'
			});
		}
		
		// 修改页面
		function tool_edit(obj,$name,$model_path,size='') {
			layer.open({
				type: 2,
				maxmin: true,
				title: '修改' + $name,
				shade: 0.1,
				area: screen(size),
				content: $model_path + 'edit/id/'+obj.data['id']
			});
		}
		
		//调用回收站
		function tool_recycle($model_path,$table) {
			layer.open({
				type: 2,
				maxmin: true,
				title: '回收站',
				shade: 0.1,
				area: screen(),
				content: $model_path + 'recycle',
				cancel: function () {
					table.reload($table);
				}
			});
		}
		
		//恢复删除的数据
		function tool_batchRecovery(obj,$name,$model_path,$table) {
			let data = table.checkStatus(obj.config.id).data;
			if (data.length === 0) {
				Alert('未选中数据',1.5);
			    return false;
			}
			var ids = []
			var hasCheck = table.checkStatus($table)
			var hasCheckData = hasCheck.data
			if (hasCheckData.length > 0) {
			    $.each(hasCheckData, function (index, element) {
			        ids.push(element.id)
			    })
			}
			confirmed('确定要恢复这些' + $name, function(index) {
			    layer.close(index);
			    let loading = layer.load();
			    $.ajax({
			        url: $model_path + 'recycle',
			        data:{ids:ids,type:true},
			        dataType: 'json',
			        type: 'POST',
			        success: function(res) {
			            //判断有没有权限
			            if(res && res.code==999){
							Alert(res.msg);
			                return false;
			            }else if(res.code==200) {
			               Alert(res.msg,'success',1,function(){
							   table.reload($table);
						   });
			            } else {
			               Alert(res.msg,'error',3);
			            }
			        },
					error: function(res){
						if(res){
							Alert(res.msg,'error',3);
						}else{
							Alert('抱歉，页面出错了！','error',3);
						}
					},
					complete: function(){
						layer.close(loading);
					},
			    })
			});
		}
		
		// 单条删除
		this.tool_remove = function(obj,$name,$model_path) {
			confirmed('确定要删除该' + $name, function(index) {
				layer.close(index);
				let loading = layer.load();
				$.ajax({
					url:$model_path + 'remove',
					data:{id:obj.data['id']},
					dataType: 'json',
					type: 'POST',
					success: function(res) {
						//判断有没有权限
						if(res && res.code==999){
							Alert(res.msg);
						    return false;
						}else if(res.code==200) {
						   Alert(res.msg,'success',1,function(){
							  obj.del(); 
						   });
						} else {
						   Alert(res.msg,'error',3);
						}
					},
					error: function(res){
						if(res){
							Alert(res.msg,'error',3);
						}else{
							Alert('抱歉，页面出错了！','error',3);
						}
					},
					complete: function(){
						layer.close(loading);
					},
				})
			});
		}
		
		// 批量软删除
		function tool_batchRemove(obj,$name,$model_path,$table) {
			let data = table.checkStatus(obj.config.id).data;
			if (data.length === 0) {
				Alert('未选中数据','info',1.5);
				return false;
			}
			var ids = []
			var hasCheck = table.checkStatus($table)
			var hasCheckData = hasCheck.data
			if (hasCheckData.length > 0) {
				$.each(hasCheckData, function (index, element) {
					ids.push(element.id)
				})
			}
			confirmed('确定要删除这些' + $name, function(index) {
				layer.close(index);
				let loading = layer.load();
				$.ajax({
					url:$model_path + 'batchRemove',
					data:{ids:ids},
					dataType: 'json',
					type: 'POST',
					success: function(res) {
						//判断有没有权限
						if(res && res.code==999){
							Alert(res.msg);
						    return false;
						}else if(res.code==200) {
						   Alert(res.msg,'success',1,function(){
								table.reload($table);
						   });
						} else {
						   Alert(res.msg,'error',3);
						}
					},
					error: function(res){
						if(res){
							Alert(res.msg,'error',3);
						}else{
							Alert('抱歉，页面出错了！','error',3);
						}
					},
					complete: function(){
						layer.close(loading);
					},
				})
			});
		}
		
		// 批量真实删除
		function tool_batchRemove2(obj,$name,$model_path,$table) {
			let data = table.checkStatus(obj.config.id).data;
			if (data.length === 0) {
				Alert('未选中数据','info',1.5);
			    return false;
			}
			var ids = []
			var hasCheck = table.checkStatus($table)
			var hasCheckData = hasCheck.data
			if (hasCheckData.length > 0) {
			    $.each(hasCheckData, function (index, element) {
			        ids.push(element.id)
			    })
			}
			confirmed('确定要彻底删除这些'+$name+'(无法恢复)', function(index) {
			    layer.close(index);
			    let loading = layer.load();
			    $.ajax({
			        url: $model_path + 'recycle',
			        data:{ids:ids},
			        dataType: 'json',
			        type: 'POST',
			        success: function(res) {
			            //判断有没有权限
						if(res && res.code==999){
							Alert(res.msg);
						    return false;
						}else if(res.code==200) {
						   Alert(res.msg,'success',1,function(){
								table.reload($table);
						   });
						} else {
						   Alert(res.msg,'error',3);
						}
			        },
					error: function(res){
						if(res){
							Alert(res.msg,'error',3);
						}else{
							Alert('抱歉，页面出错了！','error',3);
						}
					},
					complete: function(){
						layer.close(loading);
					},
			    })
			});
		}
		
		//刷新页面
		function tool_refresh(param,$table) {
			table.reload($table);
		}
		
		// 表单里面的开关修改后自动赋值文本
		form.on("switch", function(data) {
		    var val = data.elem.checked?1:0;
		    var name = this.value;
			$('[name="' + name + '"]').val(val);
		})
		
		//添加修改提交函数
		this.editSubmit = function($name='',$success,$error){
			if($name=='') $name='dataTable';
			form.on('submit(save)', function (data) {
				let myform=$(this).parents('.layui-form');				//获取提交按钮的父表单
				let type=$(this).attr('type');							//判断验证的控件属性是否按钮
				myform.find('[verify]').trigger('blur');					//验证表单内所有控件
				let numError=myform.find('.errorTips').length;
				if(numError){
					Alert('请先完善信息再提交表单','error',3);
					return false;
				}
				
				let form_data = new FormData($('.layui-form')[0]);
				load_show('数据提交中，请稍后...');
			    $.ajax({
					data: form_data,
			        dataType: 'json',
					processData: false,
			        contentType: false,
			        type: 'post',
			        success: function (res) {
						// load_hide();
			            //判断有没有权限
			            if (res && res.code == 999) {
			                Alert(res.msg);
			                return false;
			            } else if (res.code == 200) {
							Alert(res.msg,'success',1,function(){
								if(window.name!=''){
									parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
									parent.layui.table.reload($name);
								}
								if(typeof $success == "function"){
									$success(res);
								}
							});
			            } else {
			                Alert(res.msg,'error',3,function(){
								if(typeof $error == "function"){
									$success(res);
								}
							});
			            }
			        },
					error: function(res){
						if(res){
							Alert(res.msg,'error',3);
						}else{
							Alert('抱歉，页面出错了！','error',3);
						}
					},
					complete: function(){
						load_hide();
					},
			    })
			    return false;
			});
		}
        
        //动态搜索下拉菜单  initValue='名称|值'
        this.selectInput = function(elemId, ajaxUrl, initValue = '', dataKey = 'name', nameKey = 'name', transformData = null, onClickCallback = null) {
             // 初始化 initValue 和 setValue
                let initValueSplit = initValue.split('|');
                let initValueText = initValueSplit[0]; // 默认取第一个部分
                let setValueText = initValueSplit.length > 1 ? initValueSplit[1] : initValueText; // 如果有 | 分隔符，取第二部分，否则等于 initValueText
                
            // 渲染输入框
            let ins = selectInput.render({
                elem: '#' + elemId + '_search',
                name: elemId + '_input',
                hasSelectIcon:true,
                hasInitShow:true,
                inputplaceholder:'请输入关键词',
                initValue:initValueText,
                setValue:setValueText,
                data: [],
                onClick:function(data){
                    $('[name='+ elemId + ']').val(data.value);
                    
                    // 如果有传入回调函数，则执行
                    if (onClickCallback && typeof onClickCallback === 'function') {
                        onClickCallback(data);
                    }
                }
            });
            
            // 绑定输入事件（实时触发）
            $('[name='+ elemId + '_input' +']').on('input', debounce(function(event) {
                let keyword = $(this).val().trim(); // 获取输入值并去除首尾空格
                
                // 如果关键词为空，不发送请求
                if (!keyword) return;
            
                $.ajax({
                    url: ajaxUrl,
                    data: {
                        page: 1,
                        limit: 20,
                        [dataKey]: keyword, // 使用传入的dataKey作为data的键
                    },
                    type: 'get',
                    success: (res) => {
                        if (res.data && res.data.length > 0) {
                            // 使用传入的transformData函数处理数据
                            let option = transformData 
                                ? transformData(res.data) 
                                : res.data.map(item => ({
                                    name: item[nameKey],
                                    value: item.id,
                                    item: item,
                                }));
                            
                            ins.append(option, false);
                            ins.opened(); // 打开下拉框
                        } else {
                            // Alert('暂无数据！', 'error', 3);
                        }
                    },
                    error: (xhr, status, error) => {
                        Alert('请求失败，请重试！', 'error', 3);
                    }
                });
            }, 300)); // 防抖延迟300ms
            
            // 防抖函数（避免频繁触发请求）
            function debounce(func, delay) {
                let timer;
                return function() {
                    clearTimeout(timer);
                    timer = setTimeout(() => {
                        func.apply(this, arguments);
                    }, delay);
                };
            }
            
            return ins; // 返回实例化的对象
        }
	}
    
    //加载复制组件
    function initCopyFunction() {
    	// 检查 ClipboardJS 和 jQuery
    	if (typeof ClipboardJS === 'undefined' || typeof $ === 'undefined') {
    		console.warn('复制功能依赖库未加载');
    		return false;
    	}
    	
    	try {
    		var clipboard = new ClipboardJS('[copy]', {
    			text: function(trigger) {
    				return $(trigger).attr('copy');
    			}
    		});
    		
    		clipboard.on('success', function(e) {
    			setTimeout(function() {
    				Alert('复制成功！', "success", 1);
    			}, 300);
    			e.clearSelection();
    		});
    		
    		clipboard.on('error', function(e) {
    			Alert('复制失败！', "error", 3);
    			e.clearSelection();
    		});
    		
    		return true;
    	} catch (error) {
    		console.error('复制功能初始化失败:', error);
    		return false;
    	}
    }
    
	
	//弹出窗设置 自己设置弹出百分比
	function screen(size='') {
		size=size==''?0.8:size;
		var width=0;
		var height=0;
		if (typeof width !== 'number' || width === 0) {
		width = $(window).width() * size;
		}
		if (typeof height !== 'number' || height === 0) {
		height = $(window).height() - 20;
		}
		return [width + 'px', height + 'px'];
	}
	
	// $('body').on('click', '[copy]',function(){
	//     var txt=$(this).attr('copy');
	//     var clipboard = new ClipboardJS('[copy]', {
	//         text: function() {
	//             return txt;
	//         }
	//     });
	//    clipboard.on('success', function(e) {
	//        setTimeout(function() {
	//            Alert('复制成功！', "success", 1);
	//        }, 300);
	//        e.clearSelection();
	//    });
	//    clipboard.on('error', function(e) {
	//         Alert('复制失败！',"error",3);
 //            e.clearSelection();
	//     });
	// })
	
	
	//获取焦点则选中
	$('body').on('focus', '[focus-select]', function () {
		$(this).select()
	});
	
	if($('[pcshow]').length>0 && $('[mobileshow]').length>0){
	    var mobile_flag = isMobile(); // true为PC端，false为手机端
	    if(!mobile_flag){
	        $('[pcshow]').show();
	        $('[mobileshow]').hide();
	    }else{
	        $('[pcshow]').hide();
	        $('[mobileshow]').show();
	    }
	}
	
	function isMobile() {
	    var userAgentInfo = navigator.userAgent;
	
	    var mobileAgents = [ "Android", "iPhone", "SymbianOS", "Windows Phone", "iPad","iPod"];
	
	    var mobile_flag = false;
	
	    //根据userAgent判断是否是手机
	    for (var v = 0; v < mobileAgents.length; v++) {
	        if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
	            mobile_flag = true;
	            break;
	        }
	    }
	
	     var screen_width = window.screen.width;
	     var screen_height = window.screen.height;    
	
	     //根据屏幕分辨率判断是否是手机
	     if(screen_width < 500 && screen_height < 800){
	         mobile_flag = true;
	     }
	
	     return mobile_flag;
	}
	
	exports(MOD_NAME, obj);
});